<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="订单状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择订单状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.ORDER_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="订单编号" align="center" prop="id" width="180" />
      <el-table-column label="套餐名称" align="center" prop="packageName" />
      <el-table-column label="宽带速率" align="center" prop="speed" />
      <el-table-column label="订单金额" align="center" prop="totalPrice">
        <template #default="scope">
          <span class="text-red-500">¥{{ scope.row.totalPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收货信息" align="center" prop="addressInfo" min-width="200" />
      <el-table-column label="订单状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ORDER_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="支付时间"
        align="center"
        prop="payTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="120">
        <template #default="scope">
          <el-dropdown>
            <el-button link type="primary">
              更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  v-if="scope.row.status === 1"
                  @click="handlePay(scope.row)"
                >
                  去支付
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="scope.row.status === 1"
                  @click="handleCancelOrder(scope.row)"
                >
                  取消订单
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="scope.row.status === 4"
                  @click="handleFeedback(scope.row)"
                >
                  反馈
                </el-dropdown-item>
                <el-dropdown-item @click="handleViewDetail(scope.row)">
                  查看详情
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 支付确认弹窗 -->
  <el-dialog
    v-model="payDialogVisible"
    title="确认支付"
    width="400px"
    :close-on-click-modal="false"
  >
    <div class="pay-dialog-content">
      <template v-if="discount > 0">
        <p class="pay-amount">
          <span class="line-through text-gray-400">¥{{ selectedOrder?.totalPrice }}</span>
          <span class="ml-2 text-red-500">¥{{ (selectedOrder?.totalPrice! * (1 - discount / 100)).toFixed(2) }}</span>
        </p>
        <p class="pay-tips">
          {{ pointsInfo?.vipLevel === 2 ? 'VIP' : 'SVIP' }}用户享受{{ discount }}%折扣
        </p>
      </template>
      <template v-else>
        <p class="pay-amount">
          <span class="text-red-500">¥{{ selectedOrder?.totalPrice }}</span>
        </p>
      </template>
      <p class="pay-tips">确认支付该订单吗？</p>
    </div>
    <template #footer>
      <el-button @click="payDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleConfirmPay" :loading="payLoading">
        确认支付
      </el-button>
    </template>
  </el-dialog>

  <!-- 订单详情弹窗 -->
  <el-dialog
    v-model="detailDialogVisible"
    title="订单详情"
    width="600px"
    :close-on-click-modal="false"
  >
    <el-descriptions :column="2" border>
      <el-descriptions-item label="订单编号">{{ selectedOrder?.id }}</el-descriptions-item>
      <el-descriptions-item label="套餐名称">{{ selectedOrder?.packageName }}</el-descriptions-item>
      <el-descriptions-item label="宽带速率">{{ selectedOrder?.speed }}</el-descriptions-item>
      <el-descriptions-item label="订单金额">
        <span class="text-red-500">¥{{ selectedOrder?.totalPrice }}</span>
      </el-descriptions-item>
      <el-descriptions-item label="订单状态">
        <dict-tag :type="DICT_TYPE.ORDER_STATUS" :value="selectedOrder?.status" />
      </el-descriptions-item>
      <el-descriptions-item label="支付时间">
        {{ selectedOrder?.payTime || '-' }}
      </el-descriptions-item>
      <el-descriptions-item label="创建时间">
        {{ selectedOrder?.createTime || '-' }}
      </el-descriptions-item>
      <el-descriptions-item label="收货信息" :span="2">
        {{ selectedOrder?.addressInfo || '-' }}
      </el-descriptions-item>
      <el-descriptions-item label="备注信息" :span="2">
        {{ selectedOrder?.remark || '-' }}
      </el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <el-button @click="detailDialogVisible = false">关 闭</el-button>
    </template>
  </el-dialog>

  <!-- 反馈弹窗 -->
  <el-dialog
    v-model="feedbackDialogVisible"
    title="反馈"
    width="500px"
    :close-on-click-modal="false"
  >
    <el-form
      ref="feedbackFormRef"
      :model="feedbackForm"
      :rules="feedbackRules"
      label-width="80px"
    >
      <el-form-item label="反馈内容" prop="content">
        <el-input
          v-model="feedbackForm.content"
          type="textarea"
          :rows="4"
          placeholder="请输入反馈内容"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="feedbackDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmitFeedback" :loading="feedbackLoading">
        提 交
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { OrderApi, OrderVO } from '@/api/order'
import { FeedbackApi, FeedbackVO } from '@/api/feedback'
import { PointsApi, PointsRespVO } from '@/api/points'
import { useI18n } from '@/hooks/web/useI18n'
import { useMessage } from '@/hooks/web/useMessage'
import { ContentWrap } from '@/components/ContentWrap'
import { ArrowDown } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

/** 我的订单 */
defineOptions({ name: 'MyOrder' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const router = useRouter()

const loading = ref(true) // 列表的加载中
const list = ref<OrderVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  status: undefined,
  createTime: [],
})

const queryFormRef = ref() // 搜索的表单

const payDialogVisible = ref(false)
const payLoading = ref(false)
const selectedOrder = ref<OrderVO>()

const detailDialogVisible = ref(false)

const feedbackDialogVisible = ref(false)
const feedbackLoading = ref(false)
const feedbackFormRef = ref()
const feedbackForm = reactive({
  orderId: undefined,
  content: ''
})
const feedbackRules = {
  content: [{ required: true, message: '请输入反馈内容', trigger: 'blur' }]
}

const pointsInfo = ref<PointsRespVO>()
const discount = ref(0)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await OrderApi.getOrderPageByUser(queryParams)
    list.value = data.list
    total.value = data.total
  } catch (error) {
    message.error(t('common.queryError'))
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 查看订单详情 */
const handleViewDetail = (row: OrderVO) => {
  selectedOrder.value = row
  detailDialogVisible.value = true
}

/** 获取折扣信息 */
const getDiscount = async () => {
  try {
    const data = await PointsApi.getByUserId()
    pointsInfo.value = data
    // 根据VIP等级设置折扣
    switch (data.vipLevel) {
      case 2:
        discount.value = 3
        break
      case 3:
        discount.value = 5
        break
      default:
        discount.value = 0
    }
  } catch (error) {
    message.error('获取折扣信息失败')
  }
}

/** 去支付 */
const handlePay = async (row: OrderVO) => {
  selectedOrder.value = row
  payDialogVisible.value = true
  // 获取折扣信息
  await getDiscount()
}

/** 确认支付 */
const handleConfirmPay = async () => {
  if (!selectedOrder.value) return
  
  payLoading.value = true
  try {
    const now = new Date()
    const formattedDate = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`
    
    // 更新订单状态为已支付
    await OrderApi.updateOrder({
      ...selectedOrder.value,
      status: 2, // 已支付状态
      payTime: formattedDate // 使用格式化后的时间字符串
    })
    message.success('支付成功')
    payDialogVisible.value = false
    // 刷新列表
    getList()
  } catch (error) {
    message.error('支付失败')
  } finally {
    payLoading.value = false
  }
}

/** 取消订单 */
const handleCancelOrder = async (row: OrderVO) => {
  try {
    // 取消的二次确认
    await message.delConfirm('确认取消该订单吗？')
    // 更新订单状态为已取消
    await OrderApi.updateOrder({
      ...row,
      status: 5 // 已取消状态
    })
    message.success('订单已取消')
    // 刷新列表
    getList()
  } catch (error) {
    // 用户取消操作，不做处理
  }
}

/** 反馈 */
const handleFeedback = (row: OrderVO) => {
  feedbackForm.orderId = row.id
  feedbackDialogVisible.value = true
}

/** 提交反馈 */
const handleSubmitFeedback = async () => {
  if (!feedbackFormRef.value) return
  await feedbackFormRef.value.validate()
  
  feedbackLoading.value = true
  try {
    await FeedbackApi.createFeedback({
      orderId: feedbackForm.orderId!,
      content: feedbackForm.content
    })
    message.success('反馈提交成功')
    feedbackDialogVisible.value = false
    // 清空表单
    feedbackForm.content = ''
  } catch (error) {
    message.error('反馈提交失败')
  } finally {
    feedbackLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
:deep(.el-form-item__label) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

:deep(.el-form-item) {
  margin-right: 16px;
  margin-bottom: 15px;
}

.pay-dialog-content {
  text-align: center;
  padding: 20px 0;

  .pay-amount {
    font-size: 18px;
    margin-bottom: 16px;
  }

  .pay-tips {
    color: var(--el-text-color-secondary);
  }
}
</style>
